package com.iot.core.exception;

import com.iot.core.springboot.MyApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;

@Slf4j
@RestControllerAdvice
public class MyGlobalExceptionHandler {


    @ExceptionHandler(MyException.class)
    public MyApiResult handleMyException(Exception e){
        if(e instanceof  MyException me){
            var code=me.getCode()==0?999:me.getCode();
            return MyApiResult.other(code,e.getMessage(),"");
        }
        return MyApiResult.other(999,e.getMessage(),"");
    }
    @ExceptionHandler(org.springframework.dao.DuplicateKeyException.class)
    public MyApiResult handleDuplicateKeyException(Exception e){
        log.error(e.getMessage(), e);
        return MyApiResult.other(999,"数据重复",MyExceptionUtil.getMsg(e));
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public MyApiResult handleIllegalArgumentExceptionException(Exception e){
        log.error(e.getMessage(), e);
        return MyApiResult.other(999,"参数错误",MyExceptionUtil.getMsg(e) );
    }
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public MyApiResult handleIllegalHttpMessageNotReadableException(Exception e){
        log.error(e.getMessage(), e);
        return MyApiResult.other(999,"参数错误",  MyExceptionUtil.getMsg(e) );
    }

    @ExceptionHandler(NullPointerException.class)
    public MyApiResult handleNullPointerException(Exception e){
        log.error(e.getMessage(), e);

        return MyApiResult.other(999,"空指针错误",e.getMessage() );
    }
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public MyApiResult handleHttpRequestMethodNotSupportedException(Exception e){
        log.error(e.getMessage(), e);
        return MyApiResult.other(999,"不支持的 Get Post方法",e.getMessage() );
    }

    @ExceptionHandler(Exception.class)
    public MyApiResult handleException(Exception e){
        log.error(e.getMessage(), e);

        return MyApiResult.other(800, "未知异常",e.getMessage() );
    }

}
